let model = require('../model/model.js');
let time =require('../tool/gettime');
let encryption=require('../tool/encryption');
let CryptoJS=require('crypto-js');
let path =require('path');
let fs =require('fs');
const { json } = require('express');
let UserController={}
UserController.login=(req,res)=>{
    // console.log("登录页面的:"+req.session.userInfo)

    res.render('login.html',{})
}
UserController.logon=(req,res)=>{
    let {user,password} = req.body;
    username =user
    // console.log(req.session.userInfo)
   let  Private=`${password}${encryption}`;
   password=CryptoJS.MD5(Private).toString();
   req.session.userInfo = JSON.stringify({username,password})
  let sql=`SELECT * FROM userinfo WHERE username=? and password =?`
  let bind=[username,password]
//   model(sql,bind,(err,rows)=>{
//     let result= "false"
//     if(rows[0]){
//          result= "true"
//     }else{
        
//         req.session.destroy();
//     }
//     res.send(  `${result}`)
//   })
  model(sql,bind).then(rows=>{
    let result= "false"
    if(rows[0]){
         result= "true"
    }else{
        
        req.session.destroy();
    }
    res.send(  `${result}`)
  }).catch(err => console.log(err))
}
UserController.logout=(req,res)=>{
    // req.session.userInfo = JSON.stringify({});
    req.session.destroy();
    res.redirect('/login')
}
UserController.register=(req,res)=>{
    res.render('register.html',{})
}


UserController.registerOn=(req,res)=>{
 // let {fo_title,fo_cat,fo_author,fo_content} = req.body;
 let { username,password,useremail}=req.body;
 Private=`${password}${encryption}`;
 password=CryptoJS.MD5(Private).toString();
 let nowtime=time.nowtime()
 var  sql = 'INSERT INTO `Userinfo`(username,password,last_login,email) VALUES(?,?,?,?)';
 var  bind = [username,password,nowtime,useremail]; 
     model(sql,bind).then(rows=>{
      
        res.json({re_stat:"1001"})
    },err=>{             
        res.json({re_stat:"1000"})
         throw err;
     }); 
 
}
UserController.confir=(req,res)=>{
    let {eamil} =req.body;
    let sql ="SELECT * FROM userinfo WHERE email=?"
    bind=[eamil]
    model(sql,bind).then(rows=>{
        let   respon={
              is_pass :"1000"
          }
          if(rows[0]){
              respon.is_pass="1001"
          }
        res.json(respon)
      })

}
UserController.updateurl=(req,res)=>{
    // console.log("现在"+ req.session.userInfo)
    if(!req.file){
        res.json({status : "10001",message:"无上传文件"});
        return;
    }
    usermessage =JSON.parse(req.session.userInfo)
         let{ originalname,filename,destination}=req.file;
        let ext=originalname.substring(originalname.indexOf('.'));
    
        let oldPath =path.join(__dirname,"../",destination,filename);
    console.log("进入path")
        let newPath=path.join(__dirname,"../",destination,filename)+ext;
        // console.log(oldPath)
        // console.log(newPath)
        fs.renameSync(oldPath,newPath);
        winurl=destination+filename+ext;
        let sql ="UPDATE userinfo set avurl =? WHERE user_id =?"
        let bind=[winurl,usermessage.user_id]
        let  ooldpath=path.join(__dirname,'../',usermessage.avurl);
        console.log(bind)
        model(sql,bind).then(result=>{
            if(result.affectedRows){
                //修改成功则删除上一张图片fo_url
                console.log("更新头像成功")
            res.json({status : "10000",message:"修改成功",avurl:winurl})
            fs.unlink(ooldpath,()=>{console.log("删除旧头像成功")})
            usermessage.avurl =winurl;
            req.session.userInfo =JSON.stringify(usermessage)
            console.log( "更新"+req.session.userInfo)
            }
        })

}
//修改密码
UserController.uppassword=(req,res)=>{
    let {password1,password2}=req.body;
    console.log("未加密"+password2)
    let  Private=`${password1}${encryption}`;
   password1=CryptoJS.MD5(Private).toString();
    usermessage =JSON.parse(req.session.userInfo);
    password2=CryptoJS.MD5(`${password2}${encryption}`).toString();
    console.log("更改的密码"+password2)
    if(password1 !=usermessage.password){
        res.json({status : "10001",message:"原密码错误"})
        return
    }else if(password1 =usermessage.password){
        let sql ="UPDATE userinfo set password =? WHERE user_id =?"
        bind=[password2,usermessage.user_id]
        model(sql,bind).then(result=>{
            if(result.affectedRows){
                usermessage.password=password2;
                // console.log(usermessage)
                req.session.userInfo =JSON.stringify(usermessage);
                // console.log( "更新后"+req.session.userInfo)
                res.json({status : "10000",message:"修改成功"})
               
            }
        })
       
    
    }
}
module.exports=UserController;